<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>swift方法 | Albert Yuan's Blog</title><meta name="keywords" content="swift"><meta name="author" content="Albert Yuan"><meta name="copyright" content="Albert Yuan"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="referrer" content="no-referrer"><meta name="description" content="方法简介  方法是与某些特定类型相关联的函数 类、结构体、枚举既可以定义实例方法，又可以定义类型方法（类型方法与 Objective-C 中的类方法（class methods）相似）   结构体和枚举能够定义方法是 Swift 与 C&#x2F;Objective-C 的主要区别之一。在 Objective-C 中，类是唯一能定义方法的类型。但在 Swift 中，你不仅能选择是否要定义一个类&amp;#">
<meta property="og:type" content="article">
<meta property="og:title" content="swift方法">
<meta property="og:url" content="https://yllove.gitee.io/2021/08/17/Swift/swift%E6%96%B9%E6%B3%95/index.html">
<meta property="og:site_name" content="Albert Yuan&#39;s Blog">
<meta property="og:description" content="方法简介  方法是与某些特定类型相关联的函数 类、结构体、枚举既可以定义实例方法，又可以定义类型方法（类型方法与 Objective-C 中的类方法（class methods）相似）   结构体和枚举能够定义方法是 Swift 与 C&#x2F;Objective-C 的主要区别之一。在 Objective-C 中，类是唯一能定义方法的类型。但在 Swift 中，你不仅能选择是否要定义一个类&amp;#">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://programmingwithswift.com/content/images/2019/07/feature-6.png">
<meta property="article:published_time" content="2021-08-17T03:26:52.317Z">
<meta property="article:modified_time" content="2021-08-30T09:37:44.665Z">
<meta property="article:author" content="Albert Yuan">
<meta property="article:tag" content="Swift">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://programmingwithswift.com/content/images/2019/07/feature-6.png"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://yllove.gitee.io/2021/08/17/Swift/swift%E6%96%B9%E6%B3%95/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://fastly.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: {"appId":"X8NS0XSX99","apiKey":"b9d4530647c8b5bf7928a04c47752ad7","indexName":"albertyuan","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://fastly.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://fastly.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://fastly.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://fastly.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://fastly.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'swift方法',
  isPost: true,
  isHome: false,
  isHighlightShrink: true,
  isToc: true,
  postUpdate: '2021-08-30 17:37:44'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.2.0"><link rel="alternate" href="/blog/atom.xml" title="Albert Yuan's Blog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/blog/img/favicon.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">155</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">56</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">32</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://programmingwithswift.com/content/images/2019/07/feature-6.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">Albert Yuan's Blog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">swift方法</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-08-17T03:26:52.317Z" title="发表于 2021-08-17 11:26:52">2021-08-17</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-08-30T09:37:44.665Z" title="更新于 2021-08-30 17:37:44">2021-08-30</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/Swift/">Swift</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>7分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="swift方法"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h4 id="方法简介"><a href="#方法简介" class="headerlink" title="方法简介"></a>方法简介</h4><blockquote>
<ol>
<li><em>方法</em>是与某些特定类型相关联的函数</li>
<li>类、结构体、枚举既可以定义实例方法，又可以定义类型方法（类型方法与 Objective-C 中的类方法（class methods）相似）</li>
</ol>
</blockquote>
<p><strong>结构体和枚举能够定义方法是 Swift 与 C&#x2F;Objective-C 的主要区别之一。在 Objective-C 中，类是唯一能定义方法的类型。但在 Swift 中，你不仅能选择是否要定义一个类&#x2F;结构体&#x2F;枚举，还能灵活地在你创建的类型（类&#x2F;结构体&#x2F;枚举）上定义方法</strong></p>
<hr>
<h4 id="实例方法"><a href="#实例方法" class="headerlink" title="实例方法"></a>实例方法</h4><blockquote>
<ul>
<li><em>实例方法</em>是属于某个特定类、结构体或者枚举类型实例的方法</li>
<li>实例方法提供访问和修改实例属性的方法或提供与实例目的相关的功能，并以此来支撑实例的功能;</li>
<li>实例方法要写在它所属的类型的前后大括号之间</li>
<li>实例方法能够隐式访问它所属类型的所有的其他实例方法和属性</li>
<li>实例方法只能被它所属的类的某个特定实例调用</li>
</ul>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">calss <span class="type">Counter</span>&#123;</span><br><span class="line">  <span class="comment">//这个类还声明了一个可变属性 count</span></span><br><span class="line">  <span class="keyword">var</span> count <span class="operator">=</span> <span class="number">0</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">//定义了三个实例方法</span></span><br><span class="line">  <span class="keyword">func</span> <span class="title function_">increment</span>()&#123;</span><br><span class="line">    count <span class="operator">+=</span> <span class="number">1</span></span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  <span class="keyword">func</span> <span class="title function_">increment</span>(<span class="params">by</span> <span class="params">amount</span> :int)&#123;</span><br><span class="line">    count <span class="operator">+=</span> amount</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  <span class="keyword">func</span> <span class="title function_">reset</span>()&#123;</span><br><span class="line">    count <span class="operator">=</span> <span class="number">0</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> counter <span class="operator">=</span> <span class="type">Counter</span>()</span><br><span class="line">counter.increment()</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;current value is <span class="subst">\(counter.count)</span>&quot;</span>) <span class="comment">//1</span></span><br><span class="line">counter.increment(by: <span class="number">20</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;current value is <span class="subst">\(counter.count)</span>&quot;</span>) <span class="comment">//21</span></span><br><span class="line">counter.reset()</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;current value is <span class="subst">\(counter.count)</span>&quot;</span>) <span class="comment">//0</span></span><br></pre></td></tr></table></figure>

<hr>
<h5 id="self-属性"><a href="#self-属性" class="headerlink" title="self 属性"></a>self 属性</h5><blockquote>
<p>类型的每一个实例都有一个隐含属性叫做 <code>self</code>，<code>self</code> 完全等同于该实例本身。你可以在一个实例的实例方法中使用这个隐含的 <code>self</code> 属性来引用当前实例</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">func</span> <span class="title function_">increment</span>() &#123;</span><br><span class="line">    <span class="keyword">self</span>.count <span class="operator">+=</span> <span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>实际上，你不必在你的代码里面经常写 <code>self</code>。不论何时，只要在一个方法中使用一个已知的属性或者方法名称，如果你没有明确地写 <code>self</code>，Swift 假定你是指当前实例的属性或者方法。这种假定在上面的 <code>Counter</code> 中已经示范了:：<code>Counter</code> 中的三个实例方法中都使用的是 <code>count</code>（而不是 <code>self.count</code>）</p>
</blockquote>
<h6 id="明确必须使用self的情况："><a href="#明确必须使用self的情况：" class="headerlink" title="明确必须使用self的情况："></a>明确必须使用self的情况：</h6><ol>
<li><p><strong>方法参数名与属性名重名，在这种情况下，参数名称享有优先权，为避免歧义，要使用self属性来区分参数名称和属性名称</strong></p>
</li>
<li><p><strong>在逃逸闭包中引用了实例或者实例的属性，需要使用weak后的self来避免循环引用</strong>(注意循环引用问题)</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">struct</span> <span class="title class_">Point</span> &#123;</span><br><span class="line">    <span class="keyword">var</span> x <span class="operator">=</span> <span class="number">0.0</span>, y <span class="operator">=</span> <span class="number">0.0</span></span><br><span class="line">    <span class="keyword">func</span> <span class="title function_">isToTheRightOf</span>(<span class="params">x</span>: <span class="type">Double</span>) -&gt; <span class="type">Bool</span> &#123;</span><br><span class="line">      <span class="comment">//如果不使用 self 前缀，Swift会认为 x 的两个用法都引用了名为 x 的方法参数</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">self</span>.x <span class="operator">&gt;</span> x</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> somePoint <span class="operator">=</span> <span class="type">Point</span>(x: <span class="number">4.0</span>, y: <span class="number">5.0</span>)</span><br><span class="line"><span class="keyword">if</span> somePoint.isToTheRightOf(x: <span class="number">1.0</span>) &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;This point is to the right of the line where x == 1.0&quot;</span>)</span><br><span class="line">&#125;<span class="comment">// 打印“This point is to the right of the line where x == 1.0”</span></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
</ol>
<hr>
<h5 id="在实例方法中修改值类型-mutating"><a href="#在实例方法中修改值类型-mutating" class="headerlink" title="在实例方法中修改值类型:  mutating"></a>在实例方法中修改值类型:  mutating</h5><ol>
<li><strong>结构体和枚举是<em>值类型</em>。默认情况下，值类型的属性不能在它的实例方法中被修改</strong></li>
<li>如果你确实需要在某个特定的方法中修改结构体或者枚举的属性，你可以为这个方法选择 <code>可变（mutating）</code>行为,然后就可以从其方法内部改变它的属性</li>
</ol>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//要使用 可变方法，将关键字 mutating 放到方法的 func 关键字之前就可以</span></span><br><span class="line"><span class="keyword">struct</span> <span class="title class_">Point</span> &#123;</span><br><span class="line">    <span class="keyword">var</span> x <span class="operator">=</span> <span class="number">0.0</span>, y <span class="operator">=</span> <span class="number">0.0</span></span><br><span class="line">    <span class="keyword">mutating</span> <span class="keyword">func</span> <span class="title function_">moveBy</span>(<span class="params">x</span> <span class="params">deltaX</span>: <span class="type">Double</span>, <span class="params">y</span> <span class="params">deltaY</span>: <span class="type">Double</span>) &#123;</span><br><span class="line">      </span><br><span class="line">      <span class="comment">//这个方法做的任何改变都会在方法执行结束时写回到原始结构中</span></span><br><span class="line">        x <span class="operator">+=</span> deltaX</span><br><span class="line">        y <span class="operator">+=</span> deltaY</span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">  <span class="comment">//在可变方法中给 self 赋值</span></span><br><span class="line">  <span class="keyword">mutating</span> <span class="keyword">func</span> <span class="title function_">moveBy</span>(<span class="params">x</span> <span class="params">deltaX</span>: <span class="type">Double</span>, <span class="params">y</span> <span class="params">deltaY</span>: <span class="type">Double</span>) &#123;</span><br><span class="line">        <span class="keyword">self</span> <span class="operator">=</span> <span class="type">Point</span>(x: x <span class="operator">+</span> deltaX, y: y <span class="operator">+</span> deltaY)</span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">  <span class="keyword">mutating</span> <span class="keyword">func</span> <span class="title function_">reset</span>()&#123;</span><br><span class="line">    <span class="comment">//方法还可以给它隐含的 `self` 属性赋予一个全新的实例，这个新实例在方法结束时会替换现存实例</span></span><br><span class="line">    <span class="keyword">self</span> <span class="operator">=</span> <span class="type">Point</span>(x: <span class="number">0.0</span>, y: <span class="number">0.0</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//strcut 提供了默认初始化器</span></span><br><span class="line"><span class="keyword">var</span> somePoint <span class="operator">=</span> <span class="type">Point</span>(x: <span class="number">1.0</span>, y: <span class="number">1.0</span>)</span><br><span class="line"></span><br><span class="line">somePoint.moveBy(x: <span class="number">2.0</span>, y: <span class="number">3.0</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;The point is now at (<span class="subst">\(somePoint.x)</span>, <span class="subst">\(somePoint.y)</span>)&quot;</span>)<span class="comment">// 打印“The point is now at (3.0, 4.0)”</span></span><br><span class="line"></span><br><span class="line">somePoint.reset()</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;The point is now at (<span class="subst">\(somePoint.x)</span>, <span class="subst">\(somePoint.y)</span>)&quot;</span>)<span class="comment">// 打印“The point is now at (0.0, 0.0)”</span></span><br></pre></td></tr></table></figure>

<p><strong>注意：不能在结构体类型的常量（a constant of structure type）上调用可变方法，因为其属性不能被改变，即使属性是变量属性</strong></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> fixedPoint <span class="operator">=</span> <span class="type">Point</span>(x: <span class="number">3.0</span>, y: <span class="number">3.0</span>)</span><br><span class="line">fixedPoint.moveBy(x: <span class="number">2.0</span>, y: <span class="number">3.0</span>)</span><br><span class="line"><span class="comment">// 这里将会报告一个错误</span></span><br></pre></td></tr></table></figure>



<p>可变方法的枚举应用：枚举的可变方法可以把 <code>self</code> 设置为同一枚举类型中不同的成员：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//模拟点灯的点击效果：开关在不同的电源状态（off, low, high）之间循环切换</span></span><br><span class="line"><span class="keyword">enum</span> <span class="title class_">TriStateSwitch</span> &#123;</span><br><span class="line">    <span class="keyword">case</span> off, low, high</span><br><span class="line">  </span><br><span class="line">    <span class="keyword">mutating</span> <span class="keyword">func</span> <span class="title function_">next</span>() &#123;</span><br><span class="line">        <span class="keyword">switch</span> <span class="keyword">self</span> &#123;</span><br><span class="line">        <span class="keyword">case</span> .off:</span><br><span class="line">            <span class="keyword">self</span> <span class="operator">=</span> .low</span><br><span class="line">        <span class="keyword">case</span> .low:</span><br><span class="line">            <span class="keyword">self</span> <span class="operator">=</span> .high</span><br><span class="line">        <span class="keyword">case</span> .high:</span><br><span class="line">            <span class="keyword">self</span> <span class="operator">=</span> .off</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> ovenLight <span class="operator">=</span> <span class="type">TriStateSwitch</span>.low</span><br><span class="line">ovenLight.next()</span><br><span class="line"><span class="comment">// ovenLight 现在等于 .high</span></span><br><span class="line">ovenLight.next()</span><br><span class="line"><span class="comment">// ovenLight 现在等于 .off</span></span><br></pre></td></tr></table></figure>



<hr>
<h4 id="类型方法"><a href="#类型方法" class="headerlink" title="类型方法"></a>类型方法</h4><blockquote>
<ul>
<li>实例方法是被某个类型的实例调用的方法</li>
<li>定义在类型本身上调用的方法，这种方法就叫做<em>类型方法</em></li>
<li><strong>在方法的 <code>func</code> 关键字之前加上关键字 <code>static</code>，来指定类型方法</strong></li>
<li><strong>类还可以用关键字 <code>class</code> 来指定，从而允许子类重写父类该方法的实现</strong></li>
</ul>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">SomeClass</span> &#123;</span><br><span class="line">    <span class="keyword">class</span> <span class="title class_">func</span> <span class="title class_">someTypeMethod</span>() &#123;</span><br><span class="line">        <span class="comment">// 在这里实现类型方法</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="type">SomeClass</span>.someTypeMethod()</span><br></pre></td></tr></table></figure>

<ol>
<li><strong>在类型方法的方法体（body）中，<code>self</code> 属性指向这个类型本身，而不是类型的某个实例</strong>。这意味着你可以用 <code>self</code> 来消除类型属性和类型方法参数之间的歧义（类似于我们在前面处理实例属性和实例方法参数时做的那样）</li>
<li>一个类型方法可以直接通过类型方法的名称调用本类中的其它类型方法，而无需在方法名称前面加上类型名称</li>
</ol>
<p>使用样例：</p>
<p>定义了一个名为 <code>LevelTracker</code> 结构体。它监测玩家的游戏发展情况（游戏的不同层次或阶段）。这是一个单人游戏，但也可以存储多个玩家在同一设备上的游戏信息。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//等级追踪：监测玩家已解锁的最高等级</span></span><br><span class="line"><span class="keyword">struct</span> <span class="title class_">LevelTracker</span> &#123;</span><br><span class="line">  </span><br><span class="line">  	<span class="comment">//解锁的最高等级：类型存储属性</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">var</span> highestUnlockedLevel <span class="operator">=</span> <span class="number">1</span></span><br><span class="line">  </span><br><span class="line">   <span class="comment">//实例存储属性</span></span><br><span class="line">    <span class="keyword">var</span> currentLevel <span class="operator">=</span> <span class="number">1</span></span><br><span class="line"></span><br><span class="line">   <span class="comment">//类型方法 一旦新等级被解锁，它会更新 highestUnlockedLevel</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">func</span> <span class="title function_">unlock</span>(<span class="keyword">_</span> <span class="params">level</span>: <span class="type">Int</span>) &#123;</span><br><span class="line">      	<span class="comment">//这个类型方法还是能够直接访问类型属性 </span></span><br><span class="line">        <span class="keyword">if</span> level <span class="operator">&gt;</span> highestUnlockedLevel &#123; highestUnlockedLevel <span class="operator">=</span> level &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//类型方法 如果某个给定的等级已经被解锁，它将返回 true</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">func</span> <span class="title function_">isUnlocked</span>(<span class="keyword">_</span> <span class="params">level</span>: <span class="type">Int</span>) -&gt; <span class="type">Bool</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> level <span class="operator">&lt;=</span> highestUnlockedLevel</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//可变实例方法: </span></span><br><span class="line">   <span class="comment">// @discardableResult :允许在调用 advance(to:) 时候忽略返回值，不会产生编译警告，所以函数被标注为 @discardableResult 属性</span></span><br><span class="line">    <span class="keyword">@discardableResult</span> </span><br><span class="line">    <span class="keyword">mutating</span> <span class="keyword">func</span> <span class="title function_">advance</span>(<span class="params">to</span> <span class="params">level</span>: <span class="type">Int</span>) -&gt; <span class="type">Bool</span> &#123;</span><br><span class="line">      <span class="comment">//这个方法会在更新 currentLevel 之前检查所请求的新等级是否已经解锁</span></span><br><span class="line">        <span class="keyword">if</span> <span class="type">LevelTracker</span>.isUnlocked(level) &#123;</span><br><span class="line">            currentLevel <span class="operator">=</span> level</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>玩家模型：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Player</span> &#123;</span><br><span class="line">    <span class="keyword">var</span> tracker <span class="operator">=</span> <span class="type">LevelTracker</span>()</span><br><span class="line">    <span class="keyword">let</span> playerName: <span class="type">String</span></span><br><span class="line">  </span><br><span class="line">  <span class="comment">// complete(level:) 方法，一旦玩家完成某个指定等级就调用它.这个方法为所有玩家解锁下一等级，并且将当前玩家的进度更新为下一等级</span></span><br><span class="line">    <span class="keyword">func</span> <span class="title function_">complete</span>(<span class="params">level</span>: <span class="type">Int</span>) &#123;</span><br><span class="line">        <span class="type">LevelTracker</span>.unlock(level <span class="operator">+</span> <span class="number">1</span>)</span><br><span class="line">        tracker.advance(to: level <span class="operator">+</span> <span class="number">1</span>)</span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">    <span class="keyword">init</span>(<span class="params">name</span>: <span class="type">String</span>) &#123;</span><br><span class="line">        playerName <span class="operator">=</span> name</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> player <span class="operator">=</span> <span class="type">Player</span>(name: <span class="string">&quot;Argyrios&quot;</span>)</span><br><span class="line">player.complete(level: <span class="number">1</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;highest unlocked level is now <span class="subst">\(LevelTracker.highestUnlockedLevel)</span>&quot;</span>)</span><br><span class="line"><span class="comment">// 打印“highest unlocked level is now 2”</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">player <span class="operator">=</span> <span class="type">Player</span>(name: <span class="string">&quot;Beto&quot;</span>)</span><br><span class="line"><span class="keyword">if</span> player.tracker.advance(to: <span class="number">6</span>) &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;player is now on level 6&quot;</span>)</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;level 6 has not yet been unlocked&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 打印“level 6 has not yet been unlocked”</span></span><br></pre></td></tr></table></figure>



</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Albert Yuan</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://yllove.gitee.io/2021/08/17/Swift/swift%E6%96%B9%E6%B3%95/">https://yllove.gitee.io/2021/08/17/Swift/swift%E6%96%B9%E6%B3%95/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://yllove.gitee.io" target="_blank">Albert Yuan's Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/Swift/">Swift</a></div><div class="post_share"><div class="social-share" data-image="https://programmingwithswift.com/content/images/2019/07/feature-6.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://fastly.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2021/08/16/Hexo/hexo%E9%83%A8%E7%BD%B2%E5%88%B0%E7%A0%81%E4%BA%91/"><img class="prev-cover" src= "" data-lazy-src="https://img2.baidu.com/it/u=427198422,1788763367&amp;fm=15&amp;fmt=auto&amp;gp=0.jpg" onerror="onerror=null;src='/blog/img/defaultCover.gif'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">hexo部署到码云</div></div></a></div><div class="next-post pull-right"><a href="/blog/2021/08/17/Swift/swift%E4%B8%8B%E6%A0%87%E8%AF%AD%E6%B3%95/"><img class="next-cover" src= "" data-lazy-src="https://pic3.zhimg.com/80/v2-a03775e03dc4f3b971b75599c1bc2ac6_1440w.jpg" onerror="onerror=null;src='/blog/img/defaultCover.gif'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">swift下标语法</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2021/08/17/RxSwift/RxSwift初识/" title="RxSwift初识"><img class="cover" src= "" data-lazy-src="https://miro.medium.com/max/1400/1*WvSoiQrJV0Bjpau2_s9fmw.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-08-17</div><div class="title">RxSwift初识</div></div></a></div><div><a href="/blog/2021/09/15/RxSwift/RxSwift的使用详解1/" title="RxSwift的使用详解1"><img class="cover" src= "" data-lazy-src="https://www.hangge.com/blog_uploads/201801/2018010609150332714.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-15</div><div class="title">RxSwift的使用详解1</div></div></a></div><div><a href="/blog/2021/09/17/RxSwift/RxSwift的使用详解10-条件和布尔操作符/" title="RxSwift的使用详解10-条件和布尔操作符"><img class="cover" src= "" data-lazy-src="https://www.hangge.com/blog_uploads/201801/2018012419380031551.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-17</div><div class="title">RxSwift的使用详解10-条件和布尔操作符</div></div></a></div><div><a href="/blog/2021/09/16/RxSwift/RxSwift的使用详解2-响应式编程与传统编程的比较/" title="RxSwift的使用详解2-响应式编程与传统编程的比较"><img class="cover" src= "" data-lazy-src="https://www.hangge.com/blog_uploads/201801/2018010520271321260.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-16</div><div class="title">RxSwift的使用详解2-响应式编程与传统编程的比较</div></div></a></div><div><a href="/blog/2021/09/16/RxSwift/RxSwift的使用详解3-Observable介绍与创建可观察序列/" title="RxSwift的使用详解3-Observable介绍与创建可观察序列"><img class="cover" src= "" data-lazy-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.51yuansu.com%2Fpic3%2Fcover%2F00%2F90%2F36%2F58dbe747391e4_610.jpg&refer=http%3A%2F%2Fpic.51yuansu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1634356138&t=248a78e6bca1ed2479d732ae8ef28254" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-16</div><div class="title">RxSwift的使用详解3-Observable介绍与创建可观察序列</div></div></a></div><div><a href="/blog/2021/09/16/RxSwift/RxSwift的使用详解4-Observable订阅-事件监听-订阅销毁/" title="RxSwift的使用详解4-Observable订阅-事件监听-订阅销毁"><img class="cover" src= "" data-lazy-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fnimg.ws.126.net%2F%3Furl%3Dhttp%253A%252F%252Fdingyue.ws.126.net%252F2021%252F0822%252Fc74e238ej00qy8783002cc000m800ekc.jpg%26thumbnail%3D650x2147483647%26quality%3D80%26type%3Djpg&refer=http%3A%2F%2Fnimg.ws.126.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1634363191&t=72ca99f133fe4756f19a0c538c073a3e" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-16</div><div class="title">RxSwift的使用详解4-Observable订阅-事件监听-订阅销毁</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/blog/img/favicon.png" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Albert Yuan</div><div class="author-info__description">博学之,审问之,慎思之,明辨之,笃行之</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">155</div></a></div><div class="card-info-data-item is-center"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">56</div></a></div><div class="card-info-data-item is-center"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">32</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/yuanliangYL"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/yuanliangYL" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:yuanliangios@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="qq:1023817403" target="_blank" title="QQ"><i class="fab fa-qq"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">love cat , love life</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%B3%95%E7%AE%80%E4%BB%8B"><span class="toc-text">方法简介</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%9E%E4%BE%8B%E6%96%B9%E6%B3%95"><span class="toc-text">实例方法</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#self-%E5%B1%9E%E6%80%A7"><span class="toc-text">self 属性</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#%E6%98%8E%E7%A1%AE%E5%BF%85%E9%A1%BB%E4%BD%BF%E7%94%A8self%E7%9A%84%E6%83%85%E5%86%B5%EF%BC%9A"><span class="toc-text">明确必须使用self的情况：</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%9C%A8%E5%AE%9E%E4%BE%8B%E6%96%B9%E6%B3%95%E4%B8%AD%E4%BF%AE%E6%94%B9%E5%80%BC%E7%B1%BB%E5%9E%8B-mutating"><span class="toc-text">在实例方法中修改值类型:  mutating</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%B1%BB%E5%9E%8B%E6%96%B9%E6%B3%95"><span class="toc-text">类型方法</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/02/07/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS-%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BD%91%E9%A1%B5%E4%B8%8B%E8%BD%BDIPA%E5%8C%85/" title="iOS 自定义网页下载IPA包"><img src= "" data-lazy-src="https://img.mp.itc.cn/upload/20170409/1a8f793d7282451cbd1beb6841608c90_th.jpeg" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="iOS 自定义网页下载IPA包"/></a><div class="content"><a class="title" href="/blog/2023/02/07/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS-%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BD%91%E9%A1%B5%E4%B8%8B%E8%BD%BDIPA%E5%8C%85/" title="iOS 自定义网页下载IPA包">iOS 自定义网页下载IPA包</a><time datetime="2023-02-07T02:46:29.851Z" title="更新于 2023-02-07 10:46:29">2023-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/02/06/Flutter/Flutter%E6%8E%A5%E5%85%A5%E5%8E%9F%E7%94%9F-iOS/" title="flutter接入原生-iOS"><img src= "" data-lazy-src="https://pic4.zhimg.com/v2-6a115fea4db1ad770dccf4119bfab36f_1440w.jpg?source=172ae18b" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="flutter接入原生-iOS"/></a><div class="content"><a class="title" href="/blog/2023/02/06/Flutter/Flutter%E6%8E%A5%E5%85%A5%E5%8E%9F%E7%94%9F-iOS/" title="flutter接入原生-iOS">flutter接入原生-iOS</a><time datetime="2023-02-07T01:18:53.661Z" title="更新于 2023-02-07 09:18:53">2023-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/12/17/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS%20%E5%A6%82%E4%BD%95%E5%9C%A8%E6%A8%A1%E6%8B%9F%E5%99%A8%E4%B8%AD%E5%AE%89%E8%A3%85APP/" title="iOS 如何在模拟器中安装APP"><img src= "" data-lazy-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.winwin7.com%2Fuploadfile%2F2021%2F0114%2F20210114141748239.jpg&amp;refer=http%3A%2F%2Fwww.winwin7.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1673854539&amp;t=aad2108ffb799b04e94a28cc58f038f1" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="iOS 如何在模拟器中安装APP"/></a><div class="content"><a class="title" href="/blog/2022/12/17/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS%20%E5%A6%82%E4%BD%95%E5%9C%A8%E6%A8%A1%E6%8B%9F%E5%99%A8%E4%B8%AD%E5%AE%89%E8%A3%85APP/" title="iOS 如何在模拟器中安装APP">iOS 如何在模拟器中安装APP</a><time datetime="2022-12-17T07:48:56.594Z" title="更新于 2022-12-17 15:48:56">2022-12-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021/08/05/Swift/swift%E5%B8%B8%E7%94%A8%E4%B8%89%E6%96%B9%E5%BA%93/" title="swift常用三方库"><img src= "" data-lazy-src="https://photos.infinum.com/store/b558bd40787ecad225d9c66322f14522" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="swift常用三方库"/></a><div class="content"><a class="title" href="/blog/2021/08/05/Swift/swift%E5%B8%B8%E7%94%A8%E4%B8%89%E6%96%B9%E5%BA%93/" title="swift常用三方库">swift常用三方库</a><time datetime="2022-12-16T06:37:20.115Z" title="更新于 2022-12-16 14:37:20">2022-12-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/12/12/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/GCD%E8%BF%9B%E9%98%B6%E4%B9%8BDispatchWorkItem%E5%92%8CDispatchGroup/" title="GCD进阶之DispatchWorkItem和DispatchGroup"><img src= "" data-lazy-src="/blog/img/defaultCover.png" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="GCD进阶之DispatchWorkItem和DispatchGroup"/></a><div class="content"><a class="title" href="/blog/2022/12/12/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/GCD%E8%BF%9B%E9%98%B6%E4%B9%8BDispatchWorkItem%E5%92%8CDispatchGroup/" title="GCD进阶之DispatchWorkItem和DispatchGroup">GCD进阶之DispatchWorkItem和DispatchGroup</a><time datetime="2022-12-12T07:19:37.277Z" title="更新于 2022-12-12 15:19:37">2022-12-12</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://programmingwithswift.com/content/images/2019/07/feature-6.png')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Albert Yuan</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcom to my  blog</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://fastly.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/blog/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://fastly.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'REc8eytE1gJDl3d8FkudLNlL-gzGzoHsz',
      appKey: 'gGO3y8I9oVlc4Cd5N1fizNPW',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://fastly.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="255,0,0" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>